package top.humbleyuan.math;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: yuanhuanghui
 * @Date: 2020-07-24
 * @Time: 15:29
 * @Description: 整数转罗马数字
 */
public class LeetCode_12 {
    /**
     * 字符          数值
     * I             1
     * V             5
     * X             10
     * L             50
     * C             100
     * D             500
     * M             1000
     *
     * II            2
     * IV            4
     * IX            9
     */

    /**
     * 条件逻辑题，注意条件判断
     */
    public static void main(String[] args) {
        int num = 99; // 0 - 3999

        Map<Integer, String> map = buildMap();

        /**
         * 1. 从1000，100，10，1做循环
         * 2. 每个循环做余数判断，可能是0-9
         * 3. 在做多条件判断：
         * 0直接跳出
         * 1-3，循环拼接
         * 4特殊
         * 5特殊
         * 6-8，5的情况加上拼接
         * 9特殊
         */
        StringBuilder romanRes = new StringBuilder();
        int remain = num;
        for (int i = 1000; i > 0 ; i /= 10) {
            int result = remain / i;
            remain = remain % i;

            // 过了
            if(result <= 0) {
                continue;
            } else if(result <= 3) {
                // 累加
                for (int j = 0; j < result; j++) {
                    romanRes.append(map.get(i));
                }
            } else if(result == 4) {    // 4的特殊写法
                romanRes.append(map.get(i)).append(map.get(i * 5));
            } else if(result >= 5 && result < 9) {
                romanRes.append(map.get(i * 5));
                for (int j = 5; j < result; j++) {
                    romanRes.append(map.get(i));
                }
            } else if(result == 9) {
                romanRes.append(map.get(i)).append(map.get(i * 10));
            }

        }

        System.out.println(romanRes.toString());

    }

    public static Map<Integer, String> buildMap() {
        Map<Integer, String> map = new HashMap<>();
        map.put(1, "I");
        map.put(5, "V");
        map.put(10, "X");
        map.put(50, "L");
        map.put(100, "C");
        map.put(500, "D");
        map.put(1000, "M");

        return map;
    }

    /**
     * 官方题解
     */
    public static void method2() {
        int[] values = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
        String[] symbols = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
        int num = 100;

        StringBuilder sb = new StringBuilder();
        // Loop through each symbol, stopping if num becomes 0.
        for (int i = 0; i < values.length && num >= 0; i++) {
            // Repeat while the current symbol still fits into num.
            while (values[i] <= num) {
                num -= values[i];
                sb.append(symbols[i]);
            }
        }
        System.out.println(sb.toString());
    }
}
